(function(pageName){

  sugarcane.module[pageName] = function(){
    $('.j-pagescreen').addClass('fn-hide');
    var urlParams = sugarcane.getUrlParams(),timeing = null,

      docType = 1,
      voteId = urlParams['id'],
      newsId = urlParams['newsId'];
     // id = urlParams['id'];

     //dom模板
    var voteColumntpl = `
      <div class="j-waterfall">
        {@each optionList as item,index}
        <div class="j-card card-column" data-needlog="\${needLogin}" data-hasdetail="\${item.hasDescription}" data-checked="\${item.canVote}" data-status="\${interactiveStatus}" data-id="\${item.id}">
          <div class="img-box  j-jumptodetail" >
            <img src="\${item.imageUrl}">
            <div class="img-focus">
              <img src="\${item.imageUrl}">
            </div>
            {@if parseInt(index)+1 < 9}
            <span class="idxlogo">0\${parseInt(index)+1}</span>
            {@else}
            <span class="idxlogo">\${parseInt(index)+1}</span>
            {@/if}
          </div>
          <div class="card-content">
            <p class="title  j-jumptodetail"><b></b>\${item.option}</p>
            <p class="detail"><span class="j-votenum">\${item.nums}</span>票</p>
            <div class="action">
              {@if interactiveStatus == 2}
                {@if item.canVote == 0}
                <span class="btn btn-block outbtn">感谢支持</span>
                {@else}
                <span class="j-votebtn btn btn-block" data-status="\${interactiveStatus}" data-id="\${item.id}" data-needlog="\${needLogin}">投TA一票</span>
                {@/if}
              {@else if interactiveStatus == 1}
              <span class="j-votebtn btn btn-block forbidbtn" data-status="\${interactiveStatus}">暂未开始</span>
              {@else if interactiveStatus == 3}
              <span class="j-votebtn btn btn-block forbidbtn" data-status="\${interactiveStatus}">活动结束</span>
              {@/if}
            </div>
          </div>
        </div>
        {@/each}
      </div>
    `;

    var voteRowtpl = `
      <div>
        {@each optionList as item,index}
        <div class="j-card card-row " data-needlog="\${needLogin}" data-hasdetail="\${item.hasDescription}" data-checked="\${item.canVote}" data-status="\${interactiveStatus}"  data-id="\${item.id}">
          <div class="media">
            <img class="media-img j-jumptodetail" data-id="\${item.id}" src="\${item.imageUrl}">
            {@if parseInt(index)+1  < 9}
            <div class="idxlogo">0\${parseInt(index)+1 }</div>
            {@else}
            <div class="idxlogo">\${parseInt(index)+1 }</div>
            {@/if}
          </div>
          <div class="card-content">
            <p class="title j-jumptodetail" data-id="\${item.id}">\${item.option}</p>
            <p class="basic-info">
              <span class="actdata  j-jumptodetail"><span class="j-votenum">\${item.nums}</span>票</span>
              {@if  interactiveStatus == 2}
                {@if item.canVote == 0}
                <span class="btn btn-sm outbtn">感谢支持</span>
                {@else}
                <span class="j-votebtn btn btn-sm" data-status="\${interactiveStatus}" data-id="\${item.id}" data-needlog="\${needLogin}">投TA一票</span>
                {@/if}
                {@else if  interactiveStatus == 1}
                <span class="btn btn-block j-votebtn forbidbtn" data-status="\${interactiveStatus}">暂未开始</span>
                {@else if  interactiveStatus == 3}
                <span class="btn btn-block j-votebtn forbidbtn" data-status="\${interactiveStatus}">活动结束</span>
              {@/if}
            </p>
          </div>
        </div>
        {@/each}
      </div>
    `;

    var voteBigimgtpl = `
      <div>
        {@each optionList as item,index}
        <div class="j-card card-row bigimg" data-needlog="\${needLogin}" data-hasdetail="\${item.hasDescription}" data-status="\${interactiveStatus}" data-checked="\${item.canVote}" data-id="\${item.id}">
          <div class="j-jumptodetail" >
            {@if parseInt(index)+1 < 9}
            <div class="idxlogo">0\${parseInt(index)+1}</div>
            {@else}
            <div class="idxlogo">\${parseInt(index)+1}</div>
            {@/if}
            <img class="media-img" src="\${item.imageUrl}">
            <p class="title ">\${item.option}</p>
          </div>
          <p class="basic-info">
            <span class="actdata "><span class="j-votenum">\${item.nums}</span>票</span>
            {@if interactiveStatus == 2}
              {@if item.canVote == 0}
              <span class="btn btn-sm outbtn">感谢支持</span>
              {@else}
              <span class="j-votebtn btn btn-sm" data-status="\${interactiveStatus}" data-id="\${item.id}" data-needlog="\${needLogin}">投TA一票</span>
              {@/if}
              {@else if interactiveStatus == 1}
              <span class="btn btn-block j-votebtn forbidbtn" data-status="\${interactiveStatus}">暂未开始</span>
              {@else if  interactiveStatus == 3}
              <span class="btn btn-block j-votebtn forbidbtn" data-status="\${interactiveStatus}">活动结束</span>
            {@/if}
          </p>
        </div>
        {@/each}
      </div>
    `;

    var voteTxttpl = `
      <div>
        {@each optionList as item,index}
        <div class="j-card card-row cardtxt" data-needlog="\${needLogin}" data-hasdetail="\${item.hasDescription}" data-checked="\${item.canVote}" data-status="\${interactiveStatus}"  data-id="\${item.id}">
          <div class="media">

            {@if parseInt(index)+1 < 9}
            <div class="idxlogo">0\${parseInt(index)+1}</div>
            {@else}
            <div class="idxlogo">\${parseInt(index)+1}</div>
            {@/if}
          </div>
          <div class="card-content">
            <p class="title j-jumptodetail" data-id="\${item.id}">\${item.option}</p>
            <p class="basic-info">
              <span class="actdata  j-jumptodetail"><span class="j-votenum">\${item.nums}</span>票</span>
              {@if interactiveStatus == 2}
                {@if item.canVote == 0}
                <span class="btn btn-sm outbtn">感谢支持</span>
                {@else}
                <span class="j-votebtn btn btn-sm" data-status="\${interactiveStatus}" data-id="\${item.id}" data-needlog="\${needLogin}">投TA一票</span>
                {@/if}
                {@else if interactiveStatus == 1}
                <span class="btn btn-block j-votebtn forbidbtn" data-status="\${interactiveStatus}">暂未开始</span>
                {@else if interactiveStatus == 3}
                <span class="btn btn-block j-votebtn forbidbtn" data-status="\${interactiveStatus}">活动结束</span>
              {@/if}
            </p>
          </div>
        </div>
        {@/each}
      </div>
    `;
    var leadertpl = `
      <div>
        {@each data as item, index}
        <div class="lead-box" data-order="\${index}" data-count="\${item.nums}">
          <div class="left-info"></div>
          <div class="right-info media-info fn-clear">
            {@if item.imageUrl}
            <img class="headimg" src="\${item.imageUrl}">
            {@/if}
            <p>
              <span class="leadname ">\${item.option}</span>
              <span class="fn-right righttext">\${item.nums}票</span>
            </p>
          </div>
        </div>
        {@/each}
      </div>
    `;

    if ($('#j-screen-'+pageName+voteId).length) {
      var pageScreen = $('#j-screen-'+pageName+voteId);
      pageScreen.removeClass('fn-hide');
      voteShow();
      var _scrollTop = pageScreen.data('scrolltop') || 0;
      setTimeout(function(){
        $(window).scrollTop(_scrollTop);
      }, 10);
      return false;
    }



    var pageScreen = $('<div class="j-pagescreen" id="j-screen-'+pageName+voteId+'"></div>');

    pageScreen.css('background','#000');
    $('body').append(pageScreen)

    var voteObj = $( `
      <div class="app-vote">
        <div id="j-header" class="header">
          <div class="time-box">
            <div class="timebar"></div>
          </div>
        </div>
        <div class="tabbar">
          <div class="j-tab tabbar">
          <p>
              <span data-target="j-detail" class="j-tabcell tabcell tabcell-active">投票</span>
              <span data-target="j-leader" class="j-tabcell tabcell ">排名</span>
              <span data-target="j-rule" class="j-tabcell tabcell">规则</span>
            </p>
          </div>
        </div>

        <div class="tab j-detail tab-active">
          <div class="active-box">
            <p class="active-abstract fn-clear">
              已有<span id="j-joinnum">_</span>人参与
              <span id="j-activeinfo" class="btn btn-xs fn-hide fn-right">详情</span>
            </p>
            <div id="j-activeintro" class="introduct fn-hide"></div>
            <div id="j-votelist1" class="waterfall">
              <div class="leftfall"></div>
              <div class="rightfall"></div>
            </div>
          <div id="j-votelist" class="list"></div>
        </div>

        </div>
        <div class="tab j-leader"></div>
        <div class="tab j-rule">
        <div class="rule-box"></div>
        </div>
    `);

    pageScreen.append(voteObj);

    var windowheight = $(window).height();
    var tabtop = $('.j-tab').offset().top;

    $(window).scroll(function(){
      var scrollTop = $(this).scrollTop(); //页面滚动的高度
      if(scrollTop >= tabtop){
        $('.j-tab').addClass('fixed');
      }else{
        $('.j-tab').removeClass('fixed');
      }
    });

    //tab显隐
    pageScreen.find('.j-tabcell').click(function () {
      var target = $(this).data('target');
      if(target != 'j-detail'){
        if(target == 'j-leader'){
          getRankList();
        }
        pageScreen.css('background','#fff');
      }else{
        pageScreen.css('background','#000');
      }
      $(this).addClass('tabcell-active').siblings().removeClass('tabcell-active');
      $('.tab').removeClass('tab-active');
      $('.'+target).addClass('tab-active')
    });

    pageScreen.find('#j-activeinfo').click(function(){
      if( pageScreen.find('#j-activeintro').hasClass('fn-hide')){
        pageScreen.find(this).text('收起');
        pageScreen.find('#j-activeintro').removeClass('fn-hide');
      }else{
        pageScreen.find(this).text('详情');
        pageScreen.find('#j-activeintro').addClass('fn-hide');
      }
    });




    voteShow();

    function voteShow(){
      sugarcane.ajaxApi({
        "url": "/interactive/voteDetail",
        "data": {"id": voteId,"newsId": newsId},
        "callback": function(res){
          if (res['code'] == 0) {
            clearInterval(timeing);
            document.title = res.data.title;
            sugarcane.twoShare({
              "id": res.data.id,
              "title": res.data.title,
              "desc": '分享来自经济日报客户端，更多精彩请下载http://d.jingjiribao.cn/index.html',
              "imgUrl": res.data.shareImage,
              "link": res.data.shareUrl,
              "docType": res.data.docType
            });
            if(res.data.docType){
              docType = res.data.docType;
            }

            if($('#j-header').find('img').length){
              $('#j-header').find('img').attr('src',res.data['backgroundImage']);
            }else{
              $('#j-header').append('<img src="'+res.data['backgroundImage']+'">');
            }


            if(res.data['description']){
              pageScreen.find('#j-activeinfo').removeClass('fn-hide');
              pageScreen.find('#j-activeintro').html(res.data['description']);
            }

            pageScreen.find('#j-joinnum').html(res.data['participateNumber']);

            //根据type模板渲染1=二图，4=纯文字，2=左图右文，3=通栏
            if(res.data['templetType'] == '1'){
              pageScreen.find('#j-votelist1 .leftfall').html('');
              pageScreen.find('#j-votelist1 .rightfall').html('');
              var voteObj = juicer(voteColumntpl, res.data);

              $(voteObj).find('.card-column').forEach(function(item,idx){
                var leftheight  = $('#j-votelist1 .leftfall').height();
                var rightheight = $('#j-votelist1 .rightfall').height();
                if(leftheight == rightheight || leftheight < rightheight){
                  pageScreen.find('#j-votelist1 .leftfall').append(item);
                }else{
                  pageScreen.find('#j-votelist1 .rightfall').append(item);
                }

              });

            //   // 原两图标题省略样式
            //   // $('#j-votelist').html(juicer($('#j-votetpl1').html(), resData));

            }else if(res.data['templetType'] == '2'){
                var voteObj = juicer(voteRowtpl, res.data);
                pageScreen.find('#j-votelist').append(voteObj);
            }else if(res.data['templetType'] == '3'){
                var voteObj = juicer(voteBigimgtpl, res.data);
                pageScreen.find('#j-votelist').append(voteObj);
            }else if(res.data['templetType'] == '4'){
                var voteObj = juicer(voteTxttpl, res.data);
                pageScreen.find('#j-votelist').append(voteObj);
            }




            pageScreen.find('.j-rule .rule-box').html(res.data['rule']);

            if(res.data['interactiveStatus'] == 1){
              var myDate =   new Date(Date.parse(resData['startdate'].replace(/-/g,  "/")));
              var year = myDate.getFullYear();
              var month = myDate.getMonth() + 1;
              var day  = myDate.getDate();
              $('.timebar').text(year+ '年'+ month+'月'+day+'日开启').addClass('text');
            }else if(res.data['interactiveStatus'] == 2){
              gotime(res.data['startTime'], res.data['endTime']);
            }else if(res.data['interactiveStatus'] == 3){
              $('.timebar').text('活动已结束').addClass('text');
            }


            // 投票
            pageScreen.find('.j-votebtn').on(tap, function() {
              var id = $(this).data('id');
              var status = $(this).data('status');
              var needlogin = $(this).data('needlog');

              var _this = this;
              var votenum = parseInt($(this).parents('.j-card').find('.j-votenum').text());
              if(status == 1){
                // toast.success('活动暂未开始',1500);
                window.peach.toast('活动暂未开始');
              }else if(status == 2){
                submitVote(id, needlogin, function(res){
                  peach.toast(res.message);
                  if(res.data == false){//投票次数达到上限
                    $(_this).text('感谢支持').removeClass('j-votebtn').addClass('outbtn');

                    $(_this).parents('.j-card').data('checked','1');
                  }

                  votenum++;
                  $(_this).parents('.j-card').find('.j-votenum').text(votenum);
                });
              }else if(status == 3){
                // toast.success('活动已结束',1500);
                window.peach.toast('活动已结束');
              }
              return false;
            });

            //小花  点击图片跳转详情页
            ['#j-votelist','#j-votelist1'].forEach(function(item){
            // ['#j-votelist'].forEach(function(item){

              pageScreen.find(item).find('.j-jumptodetail').click(function (){
                var optionId = $(this).parents('.j-card').data('id');
                var status = $(this).parents('.j-card').data('status');
                var checked = $(this).parents('.j-card').data('checked');
                var needlog = $(this).parents('.j-card').data('needlog');
                var hasDetail = $(this).parents('.j-card').data('hasdetail');

                if(hasDetail){
                  var detailhref = 'votedetail.html?id='+ voteId +"&optionid="+ optionId +"&status="+status+"&canvote="+checked+"&needlog="+ needlog+'&newsId='+newsId;
                    if(sugarcane['app']['isShare']){
                      location.href= detailhref;
                    }else{
                      sugarcane.route.location({
                        'href': detailhref
                      });
                    }
                    

                }


              });
            });
            if(sugarcane['app']['isShare'] && !pageScreen.find('.app-banner').length ){

              sugarcane.module.load('banner', function(listitemFn){
                var bannerObj = listitemFn({'id':newsId,'docType': docType});
                pageScreen.append(bannerObj);
                var _height = $(bannerObj).css('height');
                pageScreen.css('margin-bottom',_height);
                var scrollHeight = document.documentElement.scrollHeight + parseInt(_height.slice(0,-2));
                var clientHeight = document.documentElement.clientHeight;

                if(scrollHeight < clientHeight){
                  pageScreen.css('height',clientHeight+'px');
                }else{
                  pageScreen.css('height',scrollHeight+'px');
                }
              });

            }else{
              var scrollHeight = document.documentElement.scrollHeight;
              var clientHeight = document.documentElement.clientHeight;
              if(scrollHeight < clientHeight){
                pageScreen.css('height',clientHeight+'px');
              }else{
                pageScreen.css('height',scrollHeight+'px');
              }
            }

          } else {
            showerrorView();
            peach.hiddenAppbar();
            // peach.alert(res['message']);
          }
        }
      });
    }

    // 倒计时
    function gotime(startDate, endDate){
      var startDate = + new Date(Date.parse(startDate.replace(/-/g,  "/"))),
        endDate = + new Date(Date.parse(endDate.replace(/-/g,  "/"))),
        xtimes = 0;
      function timeFn(){
        var _time = 0,serverDate = null;
          serverDate = + new Date() + xtimes;
        if (serverDate < startDate) {
          _time = startDate - serverDate;
        } else if (serverDate < endDate) {
          _time = endDate - serverDate;
        } else {
          if (timeing) clearInterval(timeing);
        }
        if (_time == 0) {
          pageScreen.find('#j-header .timebar').html('');
          return false;
        }
        var _day = Math.floor(_time / (24 * 60 * 60 * 1000));
        _time = _time % (24 * 60 * 60 * 1000);
        var _hh = Math.floor(_time / (60 * 60 * 1000));
        _time = _time % (60 * 60 * 1000);
        var _mm = Math.floor(_time / (60 * 1000));
        _time = _time % (60 * 1000);
        var _ss = Math.floor(_time / 1000);
        var _html = '';
        _html += '<span>' + _day + '</span><span>天</span>';
        _html += '<span>' + _hh + '</span><span>时</span>';
        _html += '<span>' + _mm + '</span><span>分</span>';
        // if (_day > 0) _html += '<span>' + _day + '</span><span>天</span>';
        // if (_day > 0 || _hh > 0) _html += '<span>' + _hh + '</span><span>时</span>';
        // if (_day > 0 || _hh > 0 || _mm > 0) _html += '<span>' + _mm + '</span><span>分</span>';
        _html += '<span>' + _ss + '</span><span>秒</span>';
        pageScreen.find('#j-header .timebar').html(_html);
      }
      $.ajax({cache: false, success: function(data, status, xhr){
        xtimes = + new Date(xhr.getResponseHeader('Date')) - (+ new Date());
        timeing = setInterval(timeFn, 500);
      }});
    }

    function getRankList(){
      sugarcane.ajaxApi({
        "url": "/interactive/voteRanking",
        "data": {"id": voteId,},
        "callback": function(res){
          if (res['code'] == 0) {
            var leadobj = juicer(leadertpl, res);
            pageScreen.find('.j-leader').html(juicer(leadertpl, res));
            var icon = ['first-icon', 'two-icon', 'three-icon'];
            var _count = 0,
              _order = 0;
            $('.j-leader .lead-box').each(function(){
              if ($(this).data('count') == _count) {
                $(this).data('order', _order);
              } else {
                _count = $(this).data('count');
                _order = $(this).data('order');
              }
            });
            $('.j-leader .lead-box').each(function(){
              var thisOrder = $(this).data('order');
              if (thisOrder < 3) {
                $(this).find('.left-info').addClass(icon[thisOrder]);
                $(this).find('.righttext').addClass('hoticon');
              } else {
                $(this).find('.left-info').html(thisOrder + 1);
              }
            });
          }
        }
      });
    }

    function submitVote(id, needlogin, callback){
      if (sugarcane['app']['isShare']) {
        // 去下载
        sugarcane['openApp']({'id':newsId,'docType':docType});
      } else {
        if(needlogin == '1'){//需要登录
          if (sugarcane['app']['userId']) {
            sugarcane.ajaxApi({
              "url": "/interactive/vote",
              "data": {"id": voteId,'optionId': id},
              "callback": function(res){
                if(res.code == "0"){
                  callback(res);
                }else{
                  peach.toast(res.message);
                }
              }
            });

          }else{
            // 去登录
            peach.login({
              'success': function(userInfo){
                if(userInfo['userId']) {
                  sugarcane['app']['userId'] = userInfo['userId'];
                  //刷新数据
                  voteShow();
                }
              }
            });
          }
        }else{
          sugarcane.ajaxApi({
            "url": "/interactive/vote",
            "data": {"id": voteId,'optionId': id},
            "callback": function(res){
              if(res.code == 0){
                callback(res);
              }else{
                peach.toast(res.message);
              }
            }
          });
        }
      }
    }

    function showerrorView(){
      var clientHeight = document.documentElement.clientHeight;
      pageScreen.html('');
      pageScreen.css('position','relative').css('height',clientHeight+'px').css('background','#fff');;
      var errorviewObj = $(`<div class="app-errorview">
          <img class="img" src="/static/img/isempty.png">
        <p class="error-tip">暂时没有数据</p>
      </div>`);
       pageScreen.append(errorviewObj);
    }
  }
  sugarcane.module['state'][pageName] = 'load';
  sugarcane.module.callback(pageName);
}('vote'));